package cn.sylinx.horm.core;

import java.util.List;

public class SqlPrettyHelper {

    public static String output(String sql, Object[] params) {

        StringBuilder builder = new StringBuilder();
        builder.append("\n").append("ORIGINAL SQLOUTPUT >>>> ").append(sql).append("\n");

        if (params != null && params.length > 0) {
            builder.append("ORIGINAL PARAMETER <<<< ");
            builder.append(prettyParameter(params));
        }

        return builder.toString();
    }

    private static String prettyParameter(Object parameter) {
        if (parameter instanceof List) {
            StringBuilder builder = new StringBuilder();
            builder.append("[ ");
            List<?> list = (List<?>) parameter;
            boolean empty = list.isEmpty();
            for (Object o : list) {
                builder.append(prettyParameter(o)).append(", ");
            }
            if (!empty) {
                builder.delete(builder.length() - 2, builder.length());
            }
            builder.append(" ]");
            return builder.toString();
        }

        if (parameter instanceof Object[]) {
            StringBuilder builder = new StringBuilder();
            builder.append("[ ");

            Object[] array = (Object[]) parameter;
            boolean empty = array.length == 0;
            for (Object o : array) {
                builder.append(prettyParameter(o)).append(", ");
            }
            if (!empty) {
                builder.delete(builder.length() - 2, builder.length());
            }
            builder.append(" ]");
            return builder.toString();
        }

        if (parameter == null) {
            return "null";
        }

        return parameter.toString();
    }
}
